#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python 3.13 兼容性检查和修复脚本
"""

import os
import sys
import subprocess
import warnings

def check_python_version():
    """检查Python版本"""
    print("🔍 检查Python版本...")
    version = sys.version_info
    print(f"   当前Python版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major != 3:
        print("❌ 错误: 需要Python 3.x")
        return False
    
    if version.minor < 8:
        print("⚠️  警告: 建议使用Python 3.8或更高版本")
        
    if version.minor >= 13:
        print("ℹ️  检测到Python 3.13+，将应用特定的兼容性修复")
        
    return True

def suppress_warnings():
    """抑制已知的兼容性警告"""
    print("🔧 配置警告抑制...")
    
    # 抑制NumPy的MinGW警告
    warnings.filterwarnings("ignore", message=".*MINGW-W64.*")
    warnings.filterwarnings("ignore", message=".*invalid value encountered.*")
    
    # 抑制pkg_resources废弃警告
    warnings.filterwarnings("ignore", message=".*pkg_resources is deprecated.*")
    
    # 抑制Pydantic v2配置警告
    warnings.filterwarnings("ignore", message=".*Valid config keys have changed in V2.*")
    
    print("✓ 警告抑制配置完成")

def fix_environment_variables():
    """修复环境变量"""
    print("🔧 修复环境变量...")
    
    env_vars = {
        'PYTHONIOENCODING': 'utf-8',
        'PYTHONLEGACYWINDOWSFSENCODING': '0',
        'PYTHONDONTWRITEBYTECODE': '1',  # 避免生成.pyc文件
        'PYTHONUNBUFFERED': '1'  # 确保输出立即显示
    }
    
    for key, value in env_vars.items():
        os.environ[key] = value
        print(f"✓ 设置 {key}={value}")

def check_critical_imports():
    """检查关键模块导入"""
    print("🔍 检查关键模块导入...")
    
    critical_modules = [
        ('fastapi', 'FastAPI'),
        ('uvicorn', 'Uvicorn ASGI服务器'),
        ('pydantic', 'Pydantic数据验证'),
        ('starlette', 'Starlette ASGI框架'),
        ('jose', 'JWT认证'),
        ('passlib', '密码处理'),
        ('sentence_transformers', '文本向量化'),
        ('requests', 'HTTP请求库')
    ]
    
    failed_imports = []
    
    for module_name, description in critical_modules:
        try:
            __import__(module_name)
            print(f"✓ {description} ({module_name})")
        except ImportError as e:
            print(f"❌ {description} ({module_name}): {e}")
            failed_imports.append(module_name)
    
    return failed_imports

def fix_bcrypt_compatibility():
    """修复bcrypt兼容性问题"""
    print("🔧 修复bcrypt兼容性...")
    
    try:
        import bcrypt
        import passlib
        
        # 检查bcrypt版本
        if hasattr(bcrypt, '__version__'):
            print(f"✓ bcrypt版本: {bcrypt.__version__}")
        else:
            print("⚠️  bcrypt版本信息不可用")
            
        # 测试bcrypt功能
        test_password = "test123"
        hashed = bcrypt.hashpw(test_password.encode('utf-8'), bcrypt.gensalt())
        if bcrypt.checkpw(test_password.encode('utf-8'), hashed):
            print("✓ bcrypt功能测试通过")
        else:
            print("❌ bcrypt功能测试失败")
            
    except Exception as e:
        print(f"⚠️  bcrypt兼容性问题: {e}")
        print("   这可能不会影响应用正常运行")

def check_numpy_compatibility():
    """检查NumPy兼容性"""
    print("🔍 检查NumPy兼容性...")
    
    try:
        import numpy as np
        print(f"✓ NumPy版本: {np.__version__}")
        
        # 测试基本NumPy操作
        arr = np.array([1, 2, 3])
        result = np.sum(arr)
        if result == 6:
            print("✓ NumPy基本功能测试通过")
        else:
            print("❌ NumPy基本功能测试失败")
            
    except Exception as e:
        print(f"❌ NumPy兼容性问题: {e}")

def test_web_framework():
    """测试Web框架兼容性"""
    print("🔍 测试Web框架兼容性...")
    
    try:
        from fastapi import FastAPI
        from starlette.responses import JSONResponse
        
        # 创建简单的FastAPI应用测试
        app = FastAPI()
        
        @app.get("/test")
        async def test_endpoint():
            return {"status": "ok"}
            
        print("✓ FastAPI应用创建成功")
        
    except Exception as e:
        print(f"❌ Web框架兼容性问题: {e}")

def create_compatibility_config():
    """创建兼容性配置文件"""
    print("📝 创建兼容性配置文件...")
    
    config_content = """# Python 3.13 兼容性配置
import warnings
import os

# 抑制已知的兼容性警告
warnings.filterwarnings("ignore", message=".*MINGW-W64.*")
warnings.filterwarnings("ignore", message=".*invalid value encountered.*")
warnings.filterwarnings("ignore", message=".*pkg_resources is deprecated.*")
warnings.filterwarnings("ignore", message=".*Valid config keys have changed in V2.*")

# 设置环境变量
os.environ.setdefault('PYTHONIOENCODING', 'utf-8')
os.environ.setdefault('PYTHONLEGACYWINDOWSFSENCODING', '0')

print("✓ 兼容性配置已加载")
"""

    with open("compatibility_config.py", "w", encoding="utf-8") as f:
        f.write(config_content)
    
    print("✓ 兼容性配置文件已创建: compatibility_config.py")

def main():
    """主函数"""
    print("🚀 Python 3.13 兼容性检查和修复")
    print("=" * 50)
    
    # 检查Python版本
    if not check_python_version():
        return 1
    
    print()
    
    # 抑制警告
    suppress_warnings()
    print()
    
    # 修复环境变量
    fix_environment_variables()
    print()
    
    # 检查关键模块导入
    failed_imports = check_critical_imports()
    print()
    
    # 修复特定兼容性问题
    fix_bcrypt_compatibility()
    print()
    
    check_numpy_compatibility()
    print()
    
    test_web_framework()
    print()
    
    # 创建兼容性配置
    create_compatibility_config()
    print()
    
    # 总结
    print("=" * 50)
    if failed_imports:
        print(f"⚠️  发现 {len(failed_imports)} 个模块导入失败:")
        for module in failed_imports:
            print(f"   - {module}")
        print("\n建议运行: pip install -r requirements.txt")
    else:
        print("✅ 所有关键模块导入成功!")
    
    print("\n🎯 兼容性检查完成!")
    print("\n建议:")
    print("1. 在main.py开头添加: import compatibility_config")
    print("2. 运行: python main.py --port 8005")
    
    return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)